package com.cskaoyan.controller;

import com.cskaoyan.bean.*;
import com.cskaoyan.config.MallToken;
import com.cskaoyan.service.AuthService;
import com.cskaoyan.service.LogService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.System;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * @USER: cuiweiguo#
 * @DATE: 2022/5/5
 * @TIME: 17:28
 * @PROJECT_NAME: mallproject2
 */
@RestController
@RequestMapping("admin/auth")
public class AuthController {
    @Autowired
    AuthService authService;

    @Autowired
    LogService logService;

    /**
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map, HttpServletRequest servletRequest) {
        //请求参数{"username":"admin123","password":"admin123"}
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        MallToken adminToken = new MallToken(username, password, "admin");
        String ip = servletRequest.getRemoteAddr();
        //整合shiro
        Subject subject = SecurityUtils.getSubject();
        //subject.login(new UsernamePasswordToken(username, password));
        subject.login(adminToken);
        if (subject.isAuthenticated()) {
            //////TODO:补充，验证通过之后，将登录信息写入日志中

            String admin = username;
            Integer type = 1;
            String action = "登录";
            Boolean status = true;
            String result = "ok";
            Log log = new Log(null, admin, ip, type, action, status, result, null, new Date(System.currentTimeMillis()),
                    new Date(System.currentTimeMillis()), null);
            //将log写入日志
            logService.insertLog(log);
            //认证成功，无需获得参数---但是有可能需要返回roleId---subject.getPrincipals().getPrimaryPrincipal();
            Integer userId = (Integer) subject.getPrincipals().getPrimaryPrincipal();
            LoginUserData loginUserData = new LoginUserData();
            //此时账号密码验证已经通过，所以查询数据库，返回需要的信息

            AdminInfoBean adminInfo = authService.queryAdminInfoById(userId);
            //通过userId查询数据库，获得返回的参数
            loginUserData.setAdminInfo(adminInfo);


            loginUserData.setToken((String) subject.getSession().getId());
            return BaseRespVo.ok(loginUserData);
        }else{
            //TODO:有bug，需修改
          /*  //如果没有通过验证
            String admin = username;
            Integer type = 1;
            String action = "登录";
            Boolean status = false;
            String result = "用户帐号或密码不正确";
            Log log = new Log(null, admin, ip, type, action, status, result, null, new Date(System.currentTimeMillis()),
                    new Date(System.currentTimeMillis()), null);
            //将log写入日志
            logService.insertLog(log);*/
        }

        return null;

    }

    @RequestMapping("info")
    public BaseRespVo info(String token) {





        //开发完shiro之后，再整合
        InfoData infoData = new InfoData();
        infoData.setName("admin123");

        //根据primaryPrincipal做查询
        infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        ArrayList<String> roles = new ArrayList<>();
        roles.add("超级管理员");
        infoData.setRoles(roles);
        ArrayList<String> perms = new ArrayList<>();
        perms.add("*");
        infoData.setPerms(perms);

        return BaseRespVo.ok(infoData);
    }

    @PostMapping("logout")
    public BaseRespVo logout(HttpServletRequest servletRequest) {
        //////TODO:补充，验证通过之后，将登录信息写入日志中
        Subject subject = SecurityUtils.getSubject();
        Integer userId = (Integer) subject.getPrincipals().getPrimaryPrincipal();
        //数据库查询username
        String username = authService.queryUsernameById(userId);
        String ip = servletRequest.getRemoteAddr();
        String admin = username;
        Integer type = 1;
        String action = "退出";
        Boolean status = true;
        String result = "ok";
        Log log = new Log(null, admin, ip, type, action, status, result, null, new Date(System.currentTimeMillis()),
                new Date(System.currentTimeMillis()), null);
        //将log写入日志
        logService.insertLog(log);
        //同时将登录的Ip写入admin表--表示上次登录的ip
        authService.updateIpByUserId(userId,ip);
        return BaseRespVo.out();
    }

}
